from PySide6.QtUiTools import QUiLoader
from PySide6.QtWidgets import QApplication
from PySide6.QtMultimedia import QMediaPlayer, QAudioOutput
from PySide6.QtCore import QTimer, QUrl
import os

class LoadingUi:
    def __init__(self):
        self.dir = os.path.realpath(os.curdir)
        self.play_list = os.listdir(self.dir + '/source')
        self.current_index = 0
        self.player = QMediaPlayer()
        self.audioOutput = QAudioOutput()
        self.player.setAudioOutput(self.audioOutput)
        self.ui = QUiLoader().load(self.dir + '/static/music.ui') #加载UI界面
        self.ui.pushButton.clicked.connect(self.play_music) #开始播放
        self.ui.pushButton_2.clicked.connect(self.pause_music) #暂停播放
        self.ui.pushButton_3.clicked.connect(self.previous_song) #上一曲
        self.ui.pushButton_4.clicked.connect(self.next_song) 

        self.ui.slider.sliderMoved.connect(self.set_position)
        self.ui.spinBox.setRange(0, 100)
        self.ui.spinBox.valueChanged.connect(self.set_volunm)
        self.index = 0

        #定时器监测歌曲是否播放结束
        self.end_timer = QTimer()
        self.end_timer.setInterval(500)
        self.end_timer.timeout.connect(self.check_song_end)
        #连接信号
        self.player.positionChanged.connect(self.update_position) #播放信号值
        self.player.durationChanged.connect(self.update_duration) #播放歌曲改变
        self.player.mediaStatusChanged.connect(self.handle_media_status) #播放状态改变

    def show_music(self):
        music_list = os.listdir(self.dir + '/source')
        for i in music_list:
            self.ui.textEdit.append(i)

    def play_music(self):

        if 0 <= self.index < len(self.play_list):
            self.current_index = self.index
            obs_music_path = self.dir + f'/source/{self.play_list[self.index]}'
        
            print(f'音乐播放绝对路径:{obs_music_path}')
            self.player.setSource(QUrl.fromLocalFile(obs_music_path)) #直接输入路径报错，可用QUrl替代
            self.player.play()
            self.ui.lineEdit.setText(self.play_list[self.index].split('.')[0])
            self.end_timer.start()
        print('开始播放')

    def check_song_end(self):
        """检查歌曲是否播放结束"""
        # print('检查是否播放完毕')
        if (self.player.position() >= 
            self.player.duration() - 100 and 
            self.player.duration() > 0):
            self.handle_song_end()

    def handle_song_end(self):
        """处理歌曲结束事件"""
        self.end_timer.stop()
        self.next_song()

    def next_song(self):
        """下一首"""
        print('切换歌曲')
        self.index +=1
        if self.index > len(self.play_list)-1:
            self.index = 0
            self.play_music()
            self.ui.lineEdit.setText(self.play_list[self.index].split('.')[0])
        else:
            self.play_music()
            self.ui.lineEdit.setText(self.play_list[self.index].split('.')[0])

    def previous_song(self):
        self.index -=1
        if self.index < 0:
            self.index = 0
            self.play_music()
            self.ui.lineEdit.setText(self.play_list[self.index].split('.')[0])
        else:
            self.play_music()
            self.ui.lineEdit.setText(self.play_list[self.index].split('.')[0])
            
    def pause_music(self):
        self.player.pause()
        print('暂停音乐')

    def set_position(self,position):
        self.player.setPosition(position)
        print('执行成功')

    def update_position(self, position):
        if not self.ui.slider.isSliderDown(): #判断滑块是否被用户按下
            self.ui.slider.setValue(position)

    def update_duration(self, duration):
        self.ui.slider.setRange(0,duration)  

    def handle_media_status(self, status):
        """处理媒体状态变化"""
        if status == QMediaPlayer.EndOfMedia:
            self.handle_song_end()
        elif status == QMediaPlayer.LoadedMedia:
            self.end_timer.start()
        elif status == QMediaPlayer.InvalidMedia:
            print("无法加载媒体文件")
        
    def set_volunm(self):
        value = self.ui.spinBox.value()
        self.audioOutput.setVolume(value/100 )
        print('设置成功')

if __name__ == '__main__':
    app = QApplication()
    loadingui = LoadingUi()
    loadingui.show_music()
    loadingui.ui.show()
    app.exec()
